package com.lagou.runnable;

import com.lagou.filters.TPMonitorFilter;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class Report extends FixedThreadPool implements Runnable {

    protected double percent90 = 0.9;
    protected double percent99 = 0.99;

    @Override
    public void run() {

        HashMap<String, TreeSet<TPMonitorFilter.Dimension>> statistics = TPMonitorFilter.REQUEST_STATISTICS;

        //遍历hashmap
        Set<Map.Entry<String, TreeSet<TPMonitorFilter.Dimension>>> set = statistics.entrySet();
        for (Map.Entry<String, TreeSet<TPMonitorFilter.Dimension>> entry : set) {
            String service = entry.getKey();
            TreeSet<TPMonitorFilter.Dimension> value = entry.getValue();
            report(value, service);
        }

    }

    protected void report(TreeSet<TPMonitorFilter.Dimension> statistics, String service) {
        synchronized (statistics) {
            long startTime = System.currentTimeMillis() - 60 * 1000; //获取一分钟前的时间
            for (TPMonitorFilter.Dimension data : statistics) {
                if (data.sendTime < startTime) {
                    statistics.remove(data);
                }
            }

            int size = statistics.size();
            int percent90Point = (int) (size * percent90);
            int percent99Point = (int) (size * percent99);

            TPMonitorFilter.Dimension percent90PointData = null;
            TPMonitorFilter.Dimension percent99PointData = null;
            int counter = 1;
            for (TPMonitorFilter.Dimension data : statistics) {
                if (counter == percent90Point) {
                    percent90PointData = data;
                } else if (counter == percent99Point) {
                    percent99PointData = data;
                }
                counter++;
            }

            System.out.println("=======服务" + service + "最近一分钟运行结果=====");
            System.out.println("  90分位点耗时：" + percent90PointData.spendTime);
            System.out.println("  99分位点耗时：" + percent99PointData.spendTime);
        }
    }
}
